package com.jwgf.mqtt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jwgf.mqtt.mqttactions.LengthAdjustAction;
import com.jwgf.mqtt.mqttactions.UpgradeAction;

import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;

public class VcroMqttListener implements MqttClientManager.MqttMessageListener {
    private HashMap<String, MqttAction> actionMap;

    public VcroMqttListener() {
        actionMap = new HashMap<>();
        actionMap.put("345678", new LengthAdjustAction());
        actionMap.put("upgrade", new UpgradeAction());
    }

    @Override
    public void onMessage(String topic, MqttMessage message) {
        JSONObject jsonObject = null;
        if (!topic.equals("upgrade")) {
            try {
                jsonObject = JSON.parseObject(new String(message.getPayload(), "UTF-8"));
                String key = jsonObject.getString(MqttAction.InputKeys.KEY);
                actionMap.get(key).action(jsonObject);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else {
            jsonObject = JSON.parseObject(new String(message.getPayload()));
            String key = jsonObject.getString(MqttAction.InputKeys.KEY);
            actionMap.get(key).action(jsonObject);
        }

    }
}
